package cn.com.cetccst.appstore.ui.fragment;

import static cn.com.cetccst.appstore.tools.AppAction.buttonClick;

import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import java.util.Arrays;

import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.database.model.AppModel;
import cn.com.cetccst.appstore.databinding.AdapterAppListBinding;
import cn.com.cetccst.uicomponents.binding.recyclerview.SimpleDataBindingAdapter;


public class AppListAdapter extends SimpleDataBindingAdapter<AppModel, AdapterAppListBinding> {

    private final AppListFragment.OnFragmentInteractionListener listener;

    public AppListAdapter(Context context, AppListFragment.OnFragmentInteractionListener onFragmentInteractionListener) {
        super(context, R.layout.adapter_app_list, new DiffUtil.ItemCallback<>() {
            @Override
            public boolean areItemsTheSame(@NonNull AppModel oldItem, @NonNull AppModel newItem) {
                return oldItem.getAppId().equals(newItem.getAppId());
            }

            @Override
            public boolean areContentsTheSame(@NonNull AppModel oldItem, @NonNull AppModel newItem) {
                return oldItem.getAppName().equals(newItem.getAppName())
                        && Arrays.equals(oldItem.getAppCategoryName(), newItem.getAppCategoryName())
                        && oldItem.getAppSummary().getAppVersion().equals(newItem.getAppSummary().getAppVersion())
                        && oldItem.getAppBigIconUrl().equals(newItem.getAppBigIconUrl())
                        && oldItem.getStatus().equals(newItem.getStatus())
                        && oldItem.getRange() == newItem.getRange()
                        && oldItem.isNeedUpgrade() == newItem.isNeedUpgrade();
            }
        });

        listener = onFragmentInteractionListener;

        setOnItemClickListener((item, position) -> listener.onListFragmentInteraction(item));
    }

    @Override
    protected void onBindItem(AdapterAppListBinding binding, AppModel item, RecyclerView.ViewHolder holder) {
        binding.setAppModel(item);
        ClickProxy clickProxy = binding.getClick();
        if (clickProxy != null) {
            clickProxy.setAppModel(item);
        } else {
            binding.setClick(new ClickProxy(item));
        }
    }

    public class ClickProxy {

        private AppModel appModel;

        public ClickProxy(AppModel appModel) {
            this.appModel = appModel;
        }

        public AppModel getAppModel() {
            return appModel;
        }

        public void setAppModel(AppModel appModel) {
            this.appModel = appModel;
        }

        public void buttonAction(View view) {
            buttonClick(context, appModel);
        }


    }
}
